package txtpack.Work;

import java.io.*;

public class Exam04 {
    // 使用字节输出流将一组整数写入到文件中，并使用字节输入流读取这些整数并计算它们的总和。
    public static void main(String[] args) {
        File file = new File("E:\\IO流练习\\InoutStream\\002.txt");
        int[] nums = new int[]{5, 4, 9, 2, 6, 7, 3, 2};
        writeFile(file, nums);
        int sum = readFileSum(file);
        System.out.println("文件中整数的总和为：" + sum);
    }

    private static void writeFile(File file, int[] nums) {
        try (FileOutputStream out = new FileOutputStream(file)) {
            for (int num : nums) {
                // 将整数按字节写入文件
                out.write(num);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static int readFileSum(File file) {
        int sum = 0;
        try (FileInputStream in = new FileInputStream(file)) {
            byte[] bytes = new byte[4];
            int bytesRead;
            while ((bytesRead = in.read(bytes)) != -1) {
                for (int i = 0; i < bytesRead; i += 4) {
                    int num = in.read(bytes,0,bytesRead);
                    sum += num;
                }
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return sum;
    }
}
